"""让发票明细总金额可以修改"""

from odoo import models, api, fields, _
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare


class EditAccountInoivceLine(models.Model):
    _inherit = 'account.invoice.line'

    price_subtotal = fields.Monetary(string='Amount (without Taxes)',
                                     store=True, readonly=True, compute='_compute_price',
                                     # inverse="_inverse_price_subtotal",
                                     help="Total amount without taxes")
    price_tax = fields.Monetary(string='Tax Amount', compute='_get_price_tax', store=False)
    new_price_subtotal = fields.Monetary(string='修改未税金额')

    def _get_price_tax(self):
        for l in self:
            if l.new_price_subtotal:
                l.price_tax = l.price_total - l.new_price_subtotal
            else:
                l.price_tax = l.price_total - l.price_subtotal

    @api.one
    @api.depends('new_price_subtotal', 'price_unit', 'discount', 'invoice_line_tax_ids', 'quantity',
                 'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id', 'invoice_id.company_id',
                 'invoice_id.date_invoice', 'invoice_id.date')
    def _compute_price(self):
        currency = self.invoice_id and self.invoice_id.currency_id or None
        price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
        taxes = False
        if self.invoice_line_tax_ids:
            taxes = self.invoice_line_tax_ids.compute_all(price, currency, self.quantity, product=self.product_id,
                                                          partner=self.invoice_id.partner_id)
        # ----- 改动 -----#
        if self.new_price_subtotal > 0:
            self.price_subtotal = price_subtotal_signed = self.new_price_subtotal
        else:
            self.price_subtotal = price_subtotal_signed = taxes['total_excluded'] if taxes else self.quantity * price
        # ---------------#
        self.price_total = taxes['total_included'] if taxes else self.price_subtotal
        if self.invoice_id.currency_id and self.invoice_id.currency_id != self.invoice_id.company_id.currency_id:
            currency = self.invoice_id.currency_id
            date = self.invoice_id._get_currency_rate_date()
            price_subtotal_signed = currency._convert(price_subtotal_signed, self.invoice_id.company_id.currency_id,
                                                      self.company_id or self.env.user.company_id,
                                                      date or fields.Date.today())
        sign = self.invoice_id.type in ['in_refund', 'out_refund'] and -1 or 1
        self.price_subtotal_signed = price_subtotal_signed * sign


class EditAccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.multi
    def get_taxes_values(self):
        """覆盖系统方法，目的是修改发票明细行税额的时候，手动更新税金总额"""
        tax_grouped = {}
        round_curr = self.currency_id.round
        for line in self.invoice_line_ids:
            if not line.account_id or line.display_type:
                continue
            price_unit = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.invoice_line_tax_ids.compute_all(price_unit, self.currency_id, line.quantity, line.product_id,
                                                          self.partner_id)['taxes']
            for tax in taxes:
                val = self._prepare_tax_line_vals(line, tax)
                key = self.env['account.tax'].browse(tax['id']).get_grouping_key(val)

                if key not in tax_grouped:
                    tax_grouped[key] = val
                    tax_grouped[key]['base'] = round_curr(val['base'])
                    # ----- 修改 ----#
                    if line.new_price_subtotal > 0:
                        tax_grouped[key]['amount'] = line.price_total - line.new_price_subtotal
                    # --------------#
                else:
                    # ----- 修改 ----#
                    if line.new_price_subtotal > 0:
                        tax_grouped[key]['amount'] += (line.price_total - line.new_price_subtotal)
                    else:
                        tax_grouped[key]['amount'] += val['amount']
                    # --------------#
                    tax_grouped[key]['base'] += round_curr(val['base'])
        return tax_grouped